<template>
  <div class="addPersonnel">
    <div class="addPersonnel_model">
      <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          label-width="80px"
          :validate-on-rule-change="false"
          class="demo-ruleForm"
          size="large"
          status-icon
      >
        <div class="addPersonnel_model_body">
          <el-divider content-position="left">基本信息</el-divider>
          <div class="addPersonnel_model_body_content">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="姓名" prop="name">
                  <div class="formEditDiv">
                    <div class="formEditInput">
                      <el-input v-model="ruleForm.name" :disabled="!permissions.rename"  @blur="updateName" placeholder="请输入姓名" />
                    </div>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="性别" prop="workingGroup">
                  <div class="formEditDiv">
                    <el-select style="width: 100%" :disabled="!permissions.resetMale" @change="updateMale" v-model="ruleForm.isMale" placeholder="请选择性别">
                      <el-option label="女" :value="false" />
                      <el-option label="男" :value="true" />
                    </el-select>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="所属部门" prop="department">
                  <div class="formEditDiv">
                    <div class="formEditInput">
                      <el-select @change="updateDeptId" style="width: 100%" v-model="ruleForm.deptId" placeholder="请选择部门">
                        <el-option :label="data.name" v-for="(data, index) in departments" :key="index" :value="data.id"></el-option>
                      </el-select>
                    </div>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="职务" prop="post">
                  <div class="formEditDiv">
                    <div class="formEditInput">
                      <el-select style="width: 100%" :disabled="!permissions.resetPosition" @change="updatePostition" v-model="ruleForm.officialRank" placeholder="请选择职务">
                        <el-option label="无,未明确的" value="NONE"></el-option>
                        <el-option label="负责人" value="ADMINSTRATOR"></el-option>
                        <el-option label="主管" value="DIRECTOR"></el-option>
                        <el-option label="干事" value="WOKER"></el-option>
                      </el-select>
                    </div>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>
        <div class="addPersonnel_model_body">
          <el-divider content-position="left">联系方式</el-divider>
          <div class="addPersonnel_model_body_content">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="手机号" prop="phoneNumber">
                  <div class="formEditDiv">
                    <div class="formEditInput">
                      <el-input :disabled="!permissions.resetPhoneNumber" v-model="ruleForm.phoneNumber" @blur="updatePhone" placeholder="请输入联系方式"></el-input>
                    </div>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>
        <div class="addPersonnel_model_body">
          <el-divider content-position="left">账号管理</el-divider>
          <div class="addPersonnel_model_body_content" >
            <el-form-item label="账号" prop="userName">
              <div class="formEditDiv">
                <div class="formEditInput" style="width: 100%">
                  <el-input style="width: 300px;flex-basis: 300px" v-model="ruleForm.account" readonly/>
<!--                  <el-button v-if="canAddAccount"  style="margin-left: 10px" type="primary" @click="goCreatAccount">开通账号</el-button>-->
                </div>
              </div>
            </el-form-item>
            <el-form-item label="角色" prop="role">
              <div class="formEditDiv" style="flex-wrap: wrap">
                <!-- <div class="role_search" v-if="rolesList.length !== 0">
                  <el-input size="medium" v-model="filterText" @input="filterRole"></el-input>
                </div> -->
<!--                <div class="one_role"-->
<!--                     v-for="(data, index) in permissionIdsList"-->
<!--                     :class="[ data.select === 1 ? 'click_one_role' : '' ]"-->
<!--                     :key="index"-->
<!--                     @click="testFun(data)">{{ data.description }}</div>-->
                <template v-if="filterRolesList.length === 0">
                  <div style="width: 100%;height: 40px;line-height: 40px">无</div>
                </template>

                <el-popover
                    placement="bottom-start"
                    v-for="(data, index) in filterRolesList"
                    :key="index"
                    trigger="hover">
                  <el-table :data="data.getPermissions" height="200" style="width: 400px">
                    <el-table-column  property="action" label="许可名称"></el-table-column>
                    <el-table-column  property="description" label="说明"></el-table-column>
                  </el-table>
                  <div class="one_role"
                       slot="reference"
                       :key="index"
                       @click="addOrDelRole(data)"
                       :class="[ ruleForm.role.indexOf(data.id) === -1 ? '' : 'click_one_role' ]">
                    {{ data.name }}
                  </div>
                </el-popover>
              </div>
            </el-form-item>
          </div>
        </div>
      </el-form>
    </div>
    <div class="addPersonnel_footer">
      <el-button type="primary" size="medium" @click="goPostDataFun()">返 回</el-button>
    </div>
  </div>
</template>

<script>

export default {
  name: 'editPersonnel',
  data() {
    return {
      transferProps: {
        key: 'name',
        label: 'name'
      },
      permissions: {},
      filterText: '',
      permissionIdsList: [],
      canAddAccount: false,
      options: [],
      departments: [],
      rolesList: [],
      filterRolesList: [],
      id: null,
      accountId: null,
      ruleForm: {
        name: '',
        pinyin: '',
        role: [],
        officialRank: '',
        phoneNumber: '',
        account: '',
      }
    }
  },
  computed: {
    userInfo() {
      return this.$store.state.userInfo
    },
    employeeInfo() {
      return this.$store.state.employeeInfo
    },
  },
  methods: {
    filterRole() {
      this.filterRolesList = []
      if (this.filterText === '') {
        this.filterRolesList = this.rolesList
      }else {
        this.filterRolesList = this.rolesList.filter(item => item.name.includes(this.filterText))
      }
    },
    async testFun(data) {
      let res = null
      if (data.select === 0) {
        res = await this.$axios.post('/graphql', {
          query: `mutation {
          employeeAuthorizeScene {
            authorizePermissions(
              organId: "${this.employeeInfo.organization.id}"
              employeeId: "${this.id}"
              permissionIds: ["${data.id}"]
            )
          }
        }`
        })
      }else {
        res = await this.$axios.post('/graphql', {
          query: `mutation {
          employeeAuthorizeScene {
            unauthorizePermissions(
              organId: "${this.employeeInfo.organization.id}"
              employeeId: "${this.id}"
              permissionIds: ["${data.id}"]
            )
          }
        }`
        })
      }
      if ( !res.data.errors ) {
        this.$message.success('修改成功')
        this.getPersonnel()
      }
    },
    addOrDelRole(data) {
      if (this.permissions.admin) {
        const aIndex = this.ruleForm.role.indexOf(data.id)
        if (aIndex === -1) {
          this.ruleForm.role.push(data.id)
          this.UpdateRole(data.id)
        }else {
          const roleList = []
          roleList.push(this.ruleForm.role[aIndex])
          this.ruleForm.role.splice(aIndex, 1)
          this.unauthorizeRoles(roleList)
        }
      }else {
        this.$message.success('您没有权限')
      }

    },
    async getPermissions() {
      const res = await this.$axios.post('/graphql', {
        query: `{
        authorizationQueryRepository {
          getPermissions(accountId: "${this.accountId}") {
            id
            action
            resource
          }
        }
      }`
      })
      if (!res.data.errors) {
        const arr = []
        res.data.data.authorizationQueryRepository.getPermissions.forEach(item => {
          arr.push(item.id)
        })
        this.permissionIdsList = this.permissionIdsList.map(item => {
          return {
            ...item,
            select: arr.includes(item.id) ? 1 : 0
          }
        })
      }
    },
    async UpdateRole(id) {
      const res = await this.$axios.post('/graphql', {
        query: `mutation {
          employeeAuthorizeScene {
            authorizeRoles(
              organId: "${this.employeeInfo.organization.id}",
              employeeId: "${this.id}",
              roleIds: ["${id}"]
            )
          }
        }`
      })
      if (!res.data.errors) {
        this.$message.success('已修改')
        this.getPersonnel()
      }
    },
    async unauthorizeRoles(roleList) {
      const res = await this.$axios.post('/graphql', {
        query: `mutation {
          employeeAuthorizeScene {
            unauthorizeRoles(
              organId: "${this.employeeInfo.organization.id}",
              employeeId: "${this.id}",
              roleIds: ${JSON.stringify(roleList)}
            )
          }
        }`
      })
      if (!res.data.errors) {
        this.$message.success('已取消')
        this.getPersonnel()
      }
    },
    async getTableData() {
      const res = await this.$axios.post('/graphql', {
        query: `{
        organizationQueryRepository {
          findById(id: "${this.employeeInfo.organization.id}") {
            id
            removed
            uniqueCode
            name
            shortName
            employees {
              getItems {
                id
                name
                pinyin
                phoneNumber
                officialRank
                isMale
                removed
                department {
                  id
                  name
                }
              }
            }
            departments {
              getItems {
                id
                removed
                name
                employees {
                    id
                    name
                    pinyin
                    removed
                    phoneNumber
                    officialRank
                    isMale
                    department {
                      id
                      name
                    }

                }
              }
            }
          }
        }
      }`})
      this.departments = res.data.data.organizationQueryRepository.findById.departments.getItems
    },
    async getPersonnel() {
      const id = this.$route.query.id
      const res = await this.$axios.post('/graphql', {
        query: `{
          employeeQueryRepository {
            findById(id: "${id}") {
              id
              name
              pinyin
              phoneNumber
              officialRank
              isMale
              department {
                id
                name
              }
              account {
               id
               displayName
               createDate
               isAnonymous
               actived
               loginCredentials {
                id
                domain
                identifier
               }
             }
            }
          }
          authorizationQueryRepository {
            getRoles(employeeId: "${id}") {
              id
              name
              description
            }
          }
        }`
      })
      const roles = res.data.data.authorizationQueryRepository.getRoles
      this.ruleForm = res.data.data.employeeQueryRepository.findById
      this.ruleForm.phoneNumber = res.data.data.employeeQueryRepository.findById.phoneNumber ?? ''
      this.ruleForm.role = []
      roles.forEach(item => {
        this.ruleForm.role.push(item.id)
      })
      if (res.data.data.employeeQueryRepository.findById.account && res.data.data.employeeQueryRepository.findById.account.actived) {
        this.canAddAccount = false
        this.accountId = res.data.data.employeeQueryRepository.findById.account.id
        this.ruleForm.account = res.data.data.employeeQueryRepository.findById.account.loginCredentials[0].identifier
        this.ruleForm.deptId = res.data.data.employeeQueryRepository.findById.department?.id
        await this.getPermissions()
      }else {
        this.canAddAccount = true
      }
    },
    getAuthorizationQueryRepository() {
      const organId = this.employeeInfo.organization.id
      this.permissions = {
        admin: `organization:admin:${organId}`,
        resetPhoneNumber: [
          `organization/employee:resetPhoneNumber:${organId}`,
          `organization:admin:${organId}`
        ],
        resetPosition: [
          `organization/employee:resetPosition:${organId}`,
          `organization:admin:${organId}`
        ],
        rename: [
          `organization/employee:rename:${organId}`,
          `organization:admin:${organId}`
        ],
        resetMale: [
          `organization/employee:resetMale:${organId}`,
          `organization:admin:${organId}`
        ],
      }
      const res = this.$common.checkPermissions(this.permissions)
      this.permissions = res
    },
    async goCreatAccount() {
      const id = this.$route.query.id
      const res = await this.$axios.post('/graphql', {
        query: `mutation{
          employeeManagementScene {
            creatAccount(id: "${id}")
          }
        }`
      })
      if (!res.data.errors) {
        this.$message.success('开通成功')
        this.getPersonnel()
      }else {
        this.$message.error(res.data.errors[0].message)
      }
    },
    async updateMale() {
      const res = await this.$axios.post('/graphql', {
        query: `mutation {
          employeeManagementScene {
            resetIsMale(id: "${this.id}", isMale: ${this.ruleForm.isMale})
          }
        }`
      })
      if (res.data.errors) {
        this.$message.error(res.data.errors[0].message)
      }else {
        this.getPersonnel()
        this.$message.success('已修改')
      }
    },
    async updateDeptId() {
      const res = await this.$axios.post('/graphql', {
        query: `mutation {
          employeeManagementScene {
            resetPostition(id: "${this.id}", organId: "${this.employeeInfo.organization.id}", deptId: "${this.ruleForm.deptId}")
          }
        }`
      })
      if (res.data.errors) {
        this.$message.error(res.data.errors[0].message)
      }else {
        this.getPersonnel()
        this.$message.success('已修改')
      }
    },
    async updatePostition() {
      const res = await this.$axios.post('/graphql', {
        query: `mutation {
          employeeManagementScene {
            adjuestPostition(
             id: "${this.id}"
             organId: "${this.employeeInfo.organization.id}"
             deptId: "${this.ruleForm.deptId}"
             officalRank: ${this.ruleForm.officialRank})
          }
        }`
      })
      if (res.data.errors) {
        this.$message.error(res.data.errors[0].message)
      }else {
        this.getPersonnel()
        this.$message.success('已修改')
      }
    },
    async updateName() {
      const res = await this.$axios.post('/graphql', {
        query: `mutation {
          employeeManagementScene {
            rename(id: "${this.id}", name: "${this.ruleForm.name}")
          }
        }`
      })
      if (res.data.errors) {
        this.$message.error(res.data.errors[0].message)
      }else {
        this.$message.success('已修改')
      }
    },
    async getRoleList() {
      const res = await this.$axios.post('/graphql', {
        query: `{
          roleQueryRepository {
            getRoles(organId: "${this.employeeInfo.organization.id}") {
              id
              name
              description
               department {
                id
                removed
                name
                }
                 getPermissions {
              id
              action
              description
              resource
            }
              getHolders {
                id
                name
                pinyin
                phoneNumber
                officialRank
                isMale
              }
            }
          }
        }`
      })
      this.rolesList = res.data.data.roleQueryRepository.getRoles
      this.filterRolesList = res.data.data.roleQueryRepository.getRoles
    },
    async updatePhone() {
      const res = await this.$axios.post('/graphql', {
        query: `mutation {
          employeeManagementScene {
            resetPhoneNumber(id: "${this.id}", phoneNumber: "${this.ruleForm.phoneNumber}")
          }
        }`
      })
      if (res.data.errors) {
        this.$message.error(res.data.errors[0].message)
      }else {
        this.$message.success('已修改')
      }
    },
    async getPermissionsList () {
      const res = await this.$axios.post('/graphql', {
        query: `{
          permissionTreeQueryRepository {
          getPermissionTreeByOwner(owner: "organization:${this.employeeInfo.organization.id}") {
            getItems {
              id
              action
              description
              resource
              instance
            }
            size
          }
        }
        }`
      })
      this.permissionIdsList = res.data.data.permissionTreeQueryRepository.getPermissionTreeByOwner.getItems
    },
    goPostDataFun () {
      this.$router.back()
    },
  },
  mounted() {},
  async created() {
    this.getAuthorizationQueryRepository()
    this.id = this.$route.query.id
    await this.getTableData()
    await this.getPermissionsList()
    this.getPersonnel()
    this.getRoleList()
  },
  async activated() {
    this.getAuthorizationQueryRepository()
    this.id = this.$route.query.id
    await this.getTableData()
    await this.getPermissionsList()
    this.getPersonnel()
    this.getRoleList()
  },
}

</script>

<style scoped lang="scss">
.addPersonnel {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  left: 6px;
  overflow: hidden;
  background-color: white;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.2);

  .addPersonnel_model {
    width: 100%;
    overflow: auto;
    box-sizing: border-box;
    padding: 10px 10px 10px;
    height: calc(100% - 50px);

    .addPersonnel_model_body_title {
      font-size: 18px;
      width: max-content;
      box-sizing: border-box;
      padding: 10px 50px 10px 0;
      border-bottom: 1px solid deepskyblue;
    }

    .addPersonnel_model_body_content {
      width: 100%;
      height: auto;
      box-sizing: border-box;
      padding: 15px 0;

      .operate {
        width: 100%;
        height: 100%;
        display: flex;
        display: -webkit-flex;
        display: -moz-flex;
        align-items: center;
        font-size: 22px;
      }
    }
  }

  .addPersonnel_footer {
    text-align: center;
    box-sizing: border-box;
    padding: 0 25px;
    width: 100%;
    height: 50px;
  }
}

.formEditDiv {
  width: 100%;
  height: auto;
  min-height: 40px;
  display: flex;
  display: -webkit-flex;
  display: -moz-flex;
  align-items: center;

  .formEditInput {
    width: 100%;
    flex-basis: 100%;
    flex-shrink: 0;
  }
  .formEditBtn {
    width: 40px;
    cursor: pointer;
    flex-basis: 40px;
    flex-shrink: 0;
    height: 43px;
    display: flex;
    display: -webkit-flex;
    display: -moz-flex;
    align-items: center;
    justify-content: center;
  }
}

.one_role {
  width: max-content;
  margin-bottom: 10px;
  box-sizing: border-box;
  padding: 10px 10px;
  cursor: pointer;
  border-radius: 5px;
  font-size: 14px;
  color: #a8a2a2;
  line-height: 1;
  margin-right: 10px;
  border: 1px solid #a8a2a2;

  &:hover {
    background-color: #7ac2fc;
    border-color: #7ac2fc;
    color: #FFFFFF;
  }
}

.click_one_role {
  border-color: #2f8cec;
  background-color: #2f8cec;
  color: #FFFFFF;
}

.demo-ruleForm {
  width: 100%;
  height: auto;
}

</style>
<style lang="scss">
.addPersonnel {
  .el-button {
    border-radius: 0;

  }

  .el-button--primary {
    background-color: cornflowerblue;
  }

  .el-radio-button__original-radio:checked+.el-radio-button__inner {
    background-color: cornflowerblue;
  }
}

.role_search {
  width: 100%;
  height: auto;
  margin-bottom: 10px;
}
</style>
